package com.wisely.spring_boot_security.service;

import com.wisely.spring_boot_security.dao.IUserDao;
import com.wisely.spring_boot_security.domain.SysRole;
import com.wisely.spring_boot_security.domain.SysUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

public class CustomUserService implements UserDetailsService {

    @Autowired
    private IUserDao userDao;

    @Override
    public UserDetails loadUserByUsername(String username) {
        SysUser sysUser = userDao.getUserByName(username);
        if(sysUser == null) {
            throw new UsernameNotFoundException("用户名不存在");
        }

        Long id = sysUser.getId();

        List<Map<String, Object>> sysUserRoles = userDao.listSysUserRolesByUserid(id);
        if(sysUserRoles != null && !sysUserRoles.isEmpty()) {
            List<SysRole> roles = new ArrayList<>();
            for (Map<String, Object> sysUserRole : sysUserRoles) {
                SysRole sysRole = new SysRole();
                sysRole.setId(Long.parseLong(sysUserRole.get("roleId") + ""));
                sysRole.setName(sysUserRole.get("roleName") + "");
                roles.add(sysRole);
            }

            sysUser.setRoles(roles);
        }
        return sysUser;
    }
}
